<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>历史记录 - 购销单管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Microsoft YaHei", "黑体", sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
            position: relative;
        }

        .header h1 {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 16px;
            opacity: 0.9;
        }

        .user-info {
            position: absolute;
            top: 20px;
            right: 30px;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-name {
            font-size: 14px;
            opacity: 0.9;
        }

        .logout-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
            padding: 8px 16px;
            border-radius: 20px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
        }

        .logout-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        .controls {
            padding: 20px 30px;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }

        .search-box {
            display: flex;
            align-items: center;
            gap: 10px;
            flex: 1;
            min-width: 300px;
        }

        .search-input {
            flex: 1;
            padding: 10px 15px;
            border: 2px solid #e9ecef;
            border-radius: 25px;
            font-size: 14px;
            outline: none;
            transition: all 0.3s ease;
        }

        .search-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        .stats {
            padding: 20px 30px;
            background: #f8f9fa;
            display: flex;
            justify-content: space-around;
            text-align: center;
            border-bottom: 1px solid #e9ecef;
        }

        .stat-item {
            flex: 1;
        }

        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 14px;
            color: #6c757d;
        }

        .content {
            padding: 30px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }

        .empty-state img {
            width: 120px;
            height: 120px;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .empty-state h3 {
            font-size: 20px;
            margin-bottom: 10px;
        }

        .empty-state p {
            font-size: 14px;
            margin-bottom: 20px;
        }

        .history-list {
            display: grid;
            gap: 20px;
        }

        .history-item {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 10px;
            padding: 20px;
            transition: all 0.3s ease;
            position: relative;
        }

        .history-item:hover {
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }

        .item-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 15px;
        }

        .item-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }

        .item-meta {
            font-size: 12px;
            color: #6c757d;
            display: flex;
            gap: 15px;
        }

        .item-actions {
            display: flex;
            gap: 10px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
            border-radius: 15px;
        }

        .item-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }

        .detail-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #f8f9fa;
        }

        .detail-label {
            font-weight: bold;
            color: #495057;
        }

        .detail-value {
            color: #6c757d;
        }

        .amount-highlight {
            color: #28a745;
            font-weight: bold;
            font-size: 16px;
        }

        .doc-type-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
            margin-left: 10px;
        }

        .badge-budget {
            background: #e3f2fd;
            color: #1976d2;
        }

        .badge-settlement {
            background: #e8f5e8;
            color: #2e7d32;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 30px;
            padding: 20px;
        }

        .page-btn {
            padding: 8px 12px;
            border: 1px solid #e9ecef;
            background: white;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .page-btn:hover {
            background: #f8f9fa;
        }

        .page-btn.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .page-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        @media (max-width: 768px) {
            .controls {
                flex-direction: column;
                align-items: stretch;
            }

            .search-box {
                min-width: auto;
            }

            .stats {
                flex-direction: column;
                gap: 15px;
            }

            .item-header {
                flex-direction: column;
                gap: 10px;
            }

            .item-actions {
                justify-content: flex-start;
            }

            .item-details {
                grid-template-columns: 1fr;
            }
        }

        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 6px;
            color: white;
            font-size: 14px;
            z-index: 10000;
            opacity: 0;
            transition: all 0.3s ease;
        }

        .toast.success {
            background: #28a745;
        }

        .toast.error {
            background: #dc3545;
        }

        .toast.info {
            background: #17a2b8;
        }

        .toast.show {
            opacity: 1;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="user-info">
                <span class="user-name" id="userDisplay">加载中...</span>
                <button class="logout-btn" onclick="logout()">退出</button>
            </div>
            <h1>📋 历史记录</h1>
            <p>购销单管理系统 - 查看和管理您的订单历史</p>
        </div>

        <div class="controls">
            <div class="search-box">
                <input type="text" class="search-input" id="searchInput" placeholder="搜索订单号、购货方、供货方..." onkeyup="searchHistory()">
                <button class="btn btn-secondary" onclick="searchHistory()">🔍 搜索</button>
            </div>
            <div style="display: flex; gap: 10px;">
                <a href="order.html" class="btn btn-primary">➕ 新建订单</a>
                <button class="btn btn-success" onclick="exportHistory()">📤 导出记录</button>
                <button class="btn btn-danger" onclick="clearHistory()">🗑️ 清空记录</button>
            </div>
        </div>

        <div class="stats">
            <div class="stat-item">
                <div class="stat-number" id="totalOrders">0</div>
                <div class="stat-label">总订单数</div>
            </div>
            <div class="stat-item">
                <div class="stat-number" id="totalAmount">¥0</div>
                <div class="stat-label">总金额</div>
            </div>
            <div class="stat-item">
                <div class="stat-number" id="thisMonth">0</div>
                <div class="stat-label">本月订单</div>
            </div>
        </div>

        <div class="content">
            <div id="historyContent">
                <!-- 历史记录内容将在这里动态加载 -->
            </div>
            
            <div class="pagination" id="pagination" style="display: none;">
                <!-- 分页控件将在这里动态生成 -->
            </div>
        </div>
    </div>

    <script>
        let allHistory = [];
        let filteredHistory = [];
        let currentPage = 1;
        const itemsPerPage = 10;

        // 显示消息提示
        function showToast(message, type = 'info') {
            const toast = document.createElement('div');
            toast.className = `toast ${type}`;
            toast.textContent = message;
            document.body.appendChild(toast);
            
            setTimeout(() => toast.classList.add('show'), 100);
            setTimeout(() => {
                toast.classList.remove('show');
                setTimeout(() => {
                    if (toast.parentNode) {
                        document.body.removeChild(toast);
                    }
                }, 300);
            }, 3000);
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('currentUser');
                showToast('已退出登录', 'info');
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 1000);
            }
        }

        // 加载历史记录
        function loadHistory() {
            try {
                const historyData = localStorage.getItem('orderHistory');
                console.log('从localStorage读取的数据:', historyData);
                
                if (historyData) {
                    allHistory = JSON.parse(historyData);
                    console.log('解析后的历史记录:', allHistory);
                } else {
                    allHistory = [];
                    console.log('没有找到历史记录数据');
                }
                
                filteredHistory = [...allHistory];
                updateStats();
                displayHistory();
            } catch (error) {
                console.error('加载历史记录失败:', error);
                showToast('加载历史记录失败', 'error');
                allHistory = [];
                filteredHistory = [];
                displayHistory();
            }
        }

        // 更新统计信息
        function updateStats() {
            const totalOrders = allHistory.length;
            const totalAmount = allHistory.reduce((sum, item) => {
                const amount = parseFloat(item.totalAmountNumber) || 0;
                return sum + amount;
            }, 0);
            
            const currentMonth = new Date().getMonth();
            const currentYear = new Date().getFullYear();
            const thisMonthOrders = allHistory.filter(item => {
                if (!item.saveTime) return false;
                const saveDate = new Date(item.saveTime);
                return saveDate.getMonth() === currentMonth && saveDate.getFullYear() === currentYear;
            }).length;

            document.getElementById('totalOrders').textContent = totalOrders;
            document.getElementById('totalAmount').textContent = `¥${totalAmount.toFixed(2)}`;
            document.getElementById('thisMonth').textContent = thisMonthOrders;
        }

        // 显示历史记录
        function displayHistory() {
            const content = document.getElementById('historyContent');
            
            if (filteredHistory.length === 0) {
                content.innerHTML = `
                    <div class="empty-state">
                        <div style="font-size: 60px; margin-bottom: 20px;">📋</div>
                        <h3>暂无历史记录</h3>
                        <p>您还没有保存任何订单，去创建第一个订单吧！</p>
                        <a href="order.html" class="btn btn-primary">创建新订单</a>
                    </div>
                `;
                document.getElementById('pagination').style.display = 'none';
                return;
            }

            const startIndex = (currentPage - 1) * itemsPerPage;
            const endIndex = startIndex + itemsPerPage;
            const pageItems = filteredHistory.slice(startIndex, endIndex);

            const historyHTML = pageItems.map(item => {
                const docType = item.orderNumber && item.orderNumber.includes('（结）') ? '结算' : '预算';
                const badgeClass = docType === '结算' ? 'badge-settlement' : 'badge-budget';
                
                return `
                    <div class="history-item">
                        <div class="item-header">
                            <div>
                                <div class="item-title">
                                    订单号: ${item.orderNumber || '未设置'}
                                    <span class="doc-type-badge ${badgeClass}">${docType}</span>
                                </div>
                                <div class="item-meta">
                                    <span>📅 保存时间: ${item.saveTime || '未知'}</span>
                                    <span>👤 购货方: ${item.buyer || '未填写'}</span>
                                </div>
                            </div>
                            <div class="item-actions">
                                <button class="btn btn-primary btn-sm" onclick="loadOrder('${item.orderNumber}')">📝 编辑</button>
                                <button class="btn btn-secondary btn-sm" onclick="viewOrder('${item.orderNumber}')">👁️ 查看</button>
                                <button class="btn btn-danger btn-sm" onclick="deleteOrder('${item.orderNumber}')">🗑️ 删除</button>
                            </div>
                        </div>
                        <div class="item-details">
                            <div class="detail-item">
                                <span class="detail-label">购货方:</span>
                                <span class="detail-value">${item.buyer || '未填写'}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">联系方式:</span>
                                <span class="detail-value">${item.buyerContact || '未填写'}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">订货日期:</span>
                                <span class="detail-value">${item.orderDate || '未填写'}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">送货时间:</span>
                                <span class="detail-value">${item.deliveryDate || '未填写'}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">实售金额:</span>
                                <span class="detail-value amount-highlight">¥${parseFloat(item.totalAmountNumber || 0).toFixed(2)}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">付款金额:</span>
                                <span class="detail-value">¥${parseFloat(item.currentPaymentNumber || 0).toFixed(2)}</span>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');

            content.innerHTML = `<div class="history-list">${historyHTML}</div>`;
            
            // 显示分页
            displayPagination();
        }

        // 显示分页控件
        function displayPagination() {
            const totalPages = Math.ceil(filteredHistory.length / itemsPerPage);
            const pagination = document.getElementById('pagination');
            
            if (totalPages <= 1) {
                pagination.style.display = 'none';
                return;
            }
            
            pagination.style.display = 'flex';
            
            let paginationHTML = `
                <button class="page-btn" onclick="changePage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}>上一页</button>
            `;
            
            for (let i = 1; i <= totalPages; i++) {
                if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
                    paginationHTML += `
                        <button class="page-btn ${i === currentPage ? 'active' : ''}" onclick="changePage(${i})">${i}</button>
                    `;
                } else if (i === currentPage - 3 || i === currentPage + 3) {
                    paginationHTML += `<span>...</span>`;
                }
            }
            
            paginationHTML += `
                <button class="page-btn" onclick="changePage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''}>下一页</button>
            `;
            
            pagination.innerHTML = paginationHTML;
        }

        // 切换页面
        function changePage(page) {
            const totalPages = Math.ceil(filteredHistory.length / itemsPerPage);
            if (page < 1 || page > totalPages) return;
            
            currentPage = page;
            displayHistory();
        }

        // 搜索历史记录
        function searchHistory() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase().trim();
            
            if (!searchTerm) {
                filteredHistory = [...allHistory];
            } else {
                filteredHistory = allHistory.filter(item => {
                    return (
                        (item.orderNumber && item.orderNumber.toLowerCase().includes(searchTerm)) ||
                        (item.buyer && item.buyer.toLowerCase().includes(searchTerm)) ||
                        (item.supplier && item.supplier.toLowerCase().includes(searchTerm)) ||
                        (item.buyerContact && item.buyerContact.toLowerCase().includes(searchTerm))
                    );
                });
            }
            
            currentPage = 1;
            displayHistory();
            showToast(`找到 ${filteredHistory.length} 条记录`, 'info');
        }

        // 加载订单到编辑页面
        function loadOrder(orderNumber) {
            const order = allHistory.find(item => item.orderNumber === orderNumber);
            if (order) {
                localStorage.setItem('purchaseOrderData', JSON.stringify(order));
                showToast('订单数据已加载，正在跳转...', 'success');
                setTimeout(() => {
                    window.location.href = 'order.html';
                }, 1000);
            } else {
                showToast('订单数据不存在', 'error');
            }
        }

        // 查看订单详情
        function viewOrder(orderNumber) {
            const order = allHistory.find(item => item.orderNumber === orderNumber);
            if (order) {
                // 创建详情弹窗
                const modal = document.createElement('div');
                modal.style.cssText = `
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0,0,0,0.5);
                    z-index: 10000;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding: 20px;
                `;
                
                modal.innerHTML = `
                    <div style="background: white; border-radius: 10px; padding: 30px; max-width: 600px; max-height: 80vh; overflow-y: auto;">
                        <h3 style="margin-bottom: 20px; color: #333;">订单详情 - ${order.orderNumber}</h3>
                        <div style="display: grid; gap: 10px;">
                            <div><strong>购货方:</strong> ${order.buyer || '未填写'}</div>
                            <div><strong>联系方式:</strong> ${order.buyerContact || '未填写'}</div>
                            <div><strong>供货方:</strong> ${order.supplier || '未填写'}</div>
                            <div><strong>订货日期:</strong> ${order.orderDate || '未填写'}</div>
                            <div><strong>送货时间:</strong> ${order.deliveryDate || '未填写'}</div>
                            <div><strong>收货地址:</strong> ${order.receiverAddress || '未填写'}</div>
                            <div><strong>送货方式:</strong> ${order.deliveryMethod || '未填写'}</div>
                            <div><strong>付款方式:</strong> ${order.paymentMethod || '未填写'}</div>
                            <div><strong>实售金额:</strong> <span style="color: #28a745; font-weight: bold;">¥${parseFloat(order.totalAmountNumber || 0).toFixed(2)}</span></div>
                            <div><strong>付款金额:</strong> ¥${parseFloat(order.currentPaymentNumber || 0).toFixed(2)}</div>
                            <div><strong>货款余额:</strong> ¥${parseFloat(order.balanceNumber || 0).toFixed(2)}</div>
                            <div><strong>备注:</strong> ${order.remarks || '无'}</div>
                            <div><strong>保存时间:</strong> ${order.saveTime || '未知'}</div>
                        </div>
                        <div style="text-align: center; margin-top: 20px;">
                            <button onclick="this.closest('div').parentNode.remove()" style="padding: 10px 20px; background: #6c757d; color: white; border: none; border-radius: 5px; cursor: pointer;">关闭</button>
                        </div>
                    </div>
                `;
                
                document.body.appendChild(modal);
                modal.onclick = (e) => {
                    if (e.target === modal) {
                        document.body.removeChild(modal);
                    }
                };
            }
        }

        // 删除订单
        function deleteOrder(orderNumber) {
            if (confirm(`确定要删除订单 "${orderNumber}" 吗？此操作不可恢复！`)) {
                try {
                    allHistory = allHistory.filter(item => item.orderNumber !== orderNumber);
                    localStorage.setItem('orderHistory', JSON.stringify(allHistory));
                    
                    filteredHistory = filteredHistory.filter(item => item.orderNumber !== orderNumber);
                    
                    // 如果当前页没有数据了，回到上一页
                    const totalPages = Math.ceil(filteredHistory.length / itemsPerPage);
                    if (currentPage > totalPages && totalPages > 0) {
                        currentPage = totalPages;
                    }
                    
                    updateStats();
                    displayHistory();
                    showToast('订单删除成功', 'success');
                } catch (error) {
                    console.error('删除订单失败:', error);
                    showToast('删除订单失败', 'error');
                }
            }
        }

        // 导出历史记录
        function exportHistory() {
            if (allHistory.length === 0) {
                showToast('没有可导出的记录', 'error');
                return;
            }
            
            try {
                const csvContent = generateCSV(allHistory);
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', `购销单历史记录_${new Date().toISOString().split('T')[0]}.csv`);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                showToast('历史记录导出成功', 'success');
            } catch (error) {
                console.error('导出失败:', error);
                showToast('导出失败，请重试', 'error');
            }
        }

        // 生成CSV内容
        function generateCSV(data) {
            const headers = ['订单号', '购货方', '联系方式', '订货日期', '送货时间', '实售金额', '付款金额', '货款余额', '保存时间'];
            const csvRows = [headers.join(',')];
            
            data.forEach(item => {
                const row = [
                    item.orderNumber || '',
                    item.buyer || '',
                    item.buyerContact || '',
                    item.orderDate || '',
                    item.deliveryDate || '',
                    parseFloat(item.totalAmountNumber || 0).toFixed(2),
                    parseFloat(item.currentPaymentNumber || 0).toFixed(2),
                    parseFloat(item.balanceNumber || 0).toFixed(2),
                    item.saveTime || ''
                ];
                csvRows.push(row.join(','));
            });
            
            return '\uFEFF' + csvRows.join('\n'); // 添加BOM以支持中文
        }

        // 清空历史记录
        function clearHistory() {
            if (confirm('确定要清空所有历史记录吗？此操作不可恢复！')) {
                if (confirm('请再次确认：这将删除所有保存的订单数据！')) {
                    try {
                        localStorage.removeItem('orderHistory');
                        allHistory = [];
                        filteredHistory = [];
                        currentPage = 1;
                        updateStats();
                        displayHistory();
                        showToast('历史记录已清空', 'success');
                    } catch (error) {
                        console.error('清空记录失败:', error);
                        showToast('清空记录失败', 'error');
                    }
                }
            }
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查用户登录状态
            const currentUser = localStorage.getItem('currentUser');
            if (!currentUser) {
                showToast('请先登录', 'error');
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 2000);
                return;
            }

            // 显示用户信息
            const user = JSON.parse(currentUser);
            document.getElementById('userDisplay').textContent = `欢迎，${user.username}`;

            // 加载历史记录
            loadHistory();

            // 搜索框回车事件
            document.getElementById('searchInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    searchHistory();
                }
            });
        });
    </script>
</body>
</html>